package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.PeachBlossom;


import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@DubboService
public class PeachBlossomApiImpl implements PeachBlossomApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    /**
     * 保存语音信息
     */
/*    @Override
    public void saveSound(PeachBlossom peachBlossom) {
        //因为mongodb单独保存key-value形式的数据,所以自增id字段只能以文档(集合)形式保存,所以随便给一个key做标识即可
        peachBlossom.setSid(idWorker.getNextId("peachBlossom"));
        mongoTemplate.save(peachBlossom);
    }*/
    @Override
    public PeachBlossom findVoice(long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        List<Long> ids =new ArrayList<>();
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        List<Long> friendId = CollUtil.getFieldValues(friends, "friendId", Long.class);
        ids.addAll(friendId);
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        List<Long> likeUserId = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        ids.addAll(likeUserId);
        Query query1 = new Query(Criteria.where("userId").nin(ids)).with(Sort.by(Sort.Direction.ASC,"created")).limit(10);
        List<PeachBlossom> peachBlossoms = mongoTemplate.find(query1, PeachBlossom.class);
        if (peachBlossoms == null){
            return null;
        }
     //   List<PeachBlossom> peachBlossom = mongoTemplate.findAll(PeachBlossom.class);
        return peachBlossoms.get(RandomUtil.randomInt(0, peachBlossoms.size()));

    }

    @Override
    public void saveSound(Long mobile, String soundPath) {
        PeachBlossom peachBlossom = new PeachBlossom();
        peachBlossom.setSid(idWorker.getNextId("test"));
        peachBlossom.setCreated(System.currentTimeMillis());
        peachBlossom.setSoundUrl(soundPath);
        peachBlossom.setUserId(mobile);
        mongoTemplate.save(peachBlossom);
    }
}
